import { Controller, IUpdateResult } from 'egg';

export default class FEEDBACK extends Controller {
  mysql = this.app.mysql as any;
  public async submit() {
    const { ctx } = this;
    const {name, email, telephone, content} = ctx.request.body;
    console.log('submit feedback:\n',ctx.request.body);
    ctx.validate(
      {
        'name': 'string?',
        'email': {
          type: 'email',
          required: false
        },
        'telephone': {
          type: 'telephone' ,
          require: false
        },
        'content': 'string',
      }
    );
    try {
      const row = {
        name,
        email,
        tele: telephone,
        content,
      }
      this.ctx.helper.deleteUndefined(row);
      const result:IUpdateResult = await this.mysql.insert('feedback',row);
      if (result.affectedRows>0){
        ctx.body = {
          code: 0,
          message: '成功',
          result: {
            insertId: result.insertId
          },
        };
      }else{
        ctx.body = {
          code: 1,
          message: result.message,
        };
      }
    } catch (error) {
      console.error(error);
      ctx.status = 500
      ctx.body = {
        code: 1,
        message: error.toString(),
      };
    }
  }
  public async delete() {
    const { ctx } = this;
    const id = parseInt(ctx.params.id);
    ctx.validate({
      id: 'int'
    },{
      id
    });
    console.log('delete feedback: ', id);
    try {
      const result : IUpdateResult = await this.mysql.delete('feedback',{id});  
      console.log('delete feedback:\n', result);
      
      if(result.affectedRows > 0){
        ctx.status = 204;
        ctx.body = {
          code: 0,
          message: '成功',
        };
      } else {
        ctx.status = 404;
        ctx.body = {
          code: 1,
          message: '未找到id匹配的反馈',
        };
      }
    } catch (error) {
      console.error(error);
      ctx.status = 500;
        ctx.body = {
          code: 1,
          message: error.toString(),
        };
    } 
  }
  public async get() {
    const { ctx } = this;
    const {pagesize, offset} = ctx.request.query;    
    const limit = isNaN(parseInt(pagesize))? 10 : parseInt(pagesize);
    const offset1 = isNaN(parseInt(offset))? 0 : parseInt(offset);
    console.log('get feedback: ', ctx.query, {
      limit,
      offset1,
    });
    // 暂无搜索功能
    // const where = ctx.request.query;
    try {
      const total = await this.mysql.count('feedback',{});
      const feedbacks = await this.mysql.select('feedback', {
        limit,
        offset,
      })
      
      ctx.body = {
        code: 0,
        message: '成功',
        result: {
          feedbacks
        },
        total
      }
    } catch (error) {
      console.error(error);
      ctx.status = 500,
      ctx.body = {
        code: 1,
        message: error.toString()
      }
    }
  }
}